package cn.hloger.spider.demo.webSocketDemo.service;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.util.CollectionUtils;

import javax.websocket.Session;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * session 处理类
 *
 * @author huanglong
 * @version 1.0
 * @date 2024/7/8
 */
public class SessionHandle {
    public static String getNameBySession(Session session) {
        //获取特征名
        Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
        AtomicReference<String> nameAtomic = new AtomicReference<>("未知访客");
        if (CollectionUtil.isNotEmpty(requestParameterMap)) {
            List<String> taskIdList = requestParameterMap.get("name");
            if (CollectionUtils.isEmpty(taskIdList)) {
                Optional.ofNullable(requestParameterMap.get("taskId"))
                        .map(CollectionUtil::getFirst)
                        .ifPresent(n -> nameAtomic.set(n));
            } else {
                nameAtomic.set(CollectionUtil.getFirst(taskIdList));
            }
        }
        return nameAtomic.get();
    }


    public static Session getSessionByName(String targetUser, ConcurrentHashMap<String, Session> sessionPools) {
        for (Session localSession : sessionPools.values()) {
            String name = getNameBySession(localSession);
            if (name.equals(targetUser)) {
                return localSession;
            }
        }
        return null;
    }

}
